import config.ConfigLoader;
import discovery.ServiceDiscovery;
import lombok.extern.log4j.Log4j;
import service.JsonReaderService;
import service.RPCService;
import utils.DynamicProxyFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Log4j
public class Client {

    public static void main(String[] args) throws IOException {
        ConfigLoader configLoader = new ConfigLoader("config.yml");

        ServiceDiscovery discovery = new ServiceDiscovery(configLoader.getRegistryHost() + ":" + configLoader.getRegistryPort());
        String jsonReaderServiceAddress = discovery.discoverService(JsonReaderService.class.getName());
        String rpcServiceAddress = discovery.discoverService(RPCService.class.getName());

        if (jsonReaderServiceAddress == null || rpcServiceAddress== null) {
            log.error("进程结束，服务器出现错误");
            return;
        }

        JsonReaderService jsonReaderService = (JsonReaderService) DynamicProxyFactory.getProxy(
                JsonReaderService.class, jsonReaderServiceAddress.split(":")[0], Integer.parseInt(jsonReaderServiceAddress.split(":")[1]));

        RPCService service = (RPCService) DynamicProxyFactory.getProxy(
                RPCService.class, rpcServiceAddress.split(":")[0], Integer.parseInt(rpcServiceAddress.split(":")[1]));

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("请输入操作类型（消费/充值），卡号和金额，格式：类型 卡号 金额");
        String userInput;
        while ((userInput = stdIn.readLine()) != null && !userInput.equalsIgnoreCase("quit")) {
            String json = jsonReaderService.readString(userInput);
            log.info("请求内容为：" + json);
            String result = service.request(json);
            log.info("结果为：" + result);
            System.out.println(result);
        }
    }


}